package com.infindo.frame.data.net;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.InputStreamEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

import com.infindo.frame.data.DataHandler;
import com.infindo.frame.data.DataProcessor;

@SuppressWarnings("unused")
public class RequestNewsLetterPost extends DataHandler {
	private String tag = "requestPost";
	private static final String ENCODE = "UTF-8";
	private String url;
	private String name;
    private String email;
	private DataProcessor dataProc;
	private String type;
 

	public RequestNewsLetterPost(String url, String name,String email, String type, boolean isNeedTimer, DataProcessor dataProc, int dataHandlerNo, CallbackListener listener) {
		super(dataHandlerNo, listener);
		this.setBolNeedTimer(isNeedTimer);
		this.url = url;
        this.name = name;
        this.email = email;
		this.type = type;
		this.dataProc = dataProc;
	}

	public void start() {
		new Thread(this).start();
	}

	public void run() {
		Object result = null;
		try {
			result = post(name,email, url);
		} catch (Throwable e) {
			result = e;
		}
		if (this.dataProc.checkNoCancelQueue(super.getDataHandlerNo())) {
			this.getCallbackListener().callback(type,0,result);
		}
	}

	public Object post(String name,String email, String url){
		InputStream in = null;
		OutputStream out = null;
		ByteArrayOutputStream bos = null;
		int timeoutConnection = 10000; 
		int timeoutSocket = 10000; 
		
		try{
//		HttpPost request = new HttpPost(url);
//		System.out.println("...url:"+url);
//		HttpResponse httpResponse;
//		HttpParams httpParams = new BasicHttpParams();
//		HttpConnectionParams.setConnectionTimeout(httpParams, timeoutConnection); 
//		HttpConnectionParams.setSoTimeout(httpParams, timeoutSocket); 
//		
//		String jsonString = "{\"CustomFields[13]\":\""+name+",\"email\":\""+email+"\"}";
//		
//		Log.v("jsonString",jsonString);
//		
//		
//		
//		ByteArrayInputStream bais = new ByteArrayInputStream(jsonString.getBytes());
//
//		InputStreamEntity ise = new InputStreamEntity(bais, jsonString.getBytes().length);
//		ise.setContentType("binary/octet-stream");
//		ise.setChunked(true);
//		request.setEntity(ise);
		
//		Log.e("url", url+"  name:"+name+"  email:"+email);
		HttpPost httpPost =new HttpPost(url);
		List <NameValuePair> params=new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("CustomFields[13]",name));
		params.add(new BasicNameValuePair("email",email));
		httpPost.setEntity(new  UrlEncodedFormEntity(params,HTTP.UTF_8));
		
		
//	    request.addHeader("CustomFields[13]", name);
//	    request.addHeader("email",email);
		
		startConnect();
		dataProc.getDataTimer().addConnect(this);
		

		String result = "";
 
			 HttpResponse httpResponse=new  DefaultHttpClient().execute(httpPost);
			 int code = httpResponse.getStatusLine().getStatusCode();
//			 Log.e("code", ""+code);
			if (code == 200) {   
				HttpEntity entity = httpResponse.getEntity();
		        //取得数据记录内容
		        InputStream is = entity.getContent();
		        //显示数据记录内容
		        InputStreamReader isr = new InputStreamReader(is, ENCODE);
				BufferedReader br = new BufferedReader(isr);
		        String str = "";//in.readLine();
		        StringBuffer s = new StringBuffer("");
		        while((str = br.readLine()) != null){   
		          s.append(str);  
		        
		      }
		        result = "ok";
            }   

			if(result != null & !"".equals(result)){
 
			}
			try {
//				JSONObject outer = new JSONObject(result);
//				System.out.println("outer :"+outer);
//				return outer;
				return result.toString();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} catch (UnsupportedEncodingException e) {
//			System.out.println("error :"+e.getMessage());
			return null;
		} catch (ClientProtocolException e) {
//			System.out.println("error :"+e.getMessage());
			return null;
		} catch (IOException e) {
//			System.out.println("error :"+e.getMessage());
			return null;
		}

		return null;
	}
//	public Object post(String content, String url) {
//		InputStream in = null;
//		OutputStream out = null;
//		ByteArrayOutputStream bos = null;
//		Log.i("", "req:@" + content);
//
//		try {
//			byte[] postdata = content.getBytes(ENCODE);
//			HttpParams httpParams = new BasicHttpParams();
//			HttpConnectionParams.setConnectionTimeout(httpParams, Const.CONNECT_HTTP_TIMEOUT);
//			HttpConnectionParams.setSoTimeout(httpParams, Const.CONNECT_SOCKET_TIMEOUT);
//			HttpClient httpClient = new DefaultHttpClient(httpParams);
//
//			HttpPost httpPost = new HttpPost(url);
//
//			ByteArrayInputStream bais = new ByteArrayInputStream(postdata);
//
//			InputStreamEntity ise = new InputStreamEntity(bais, 1024);
//			ise.setContentType("binary/octet-stream");
//			ise.setChunked(true);
//			httpPost.setEntity(ise);
//
//			httpPost.addHeader("X-UserAgent", "EPL/ANDROID/1.0");
//
//			HttpResponse response = httpClient.execute(httpPost);
//			HttpEntity entity = response.getEntity();
//
//			StringBuffer strBuf = new StringBuffer();
//			if (entity != null) {
//				InputStream is = entity.getContent();
//				InputStreamReader isr = new InputStreamReader(is, ENCODE);
//				BufferedReader br = new BufferedReader(isr);
//				String line;
//				while ((line = br.readLine()) != null) {
//					strBuf.append(line);
//				}
//				is.close();
//
//				// Consume response content
//				entity.consumeContent();
//
//			}
//			httpClient.getConnectionManager().shutdown();
//			if (strBuf.toString() == null || "".equals(strBuf.toString()))
//				return null;
//			try {
//				Log.i("", "msg 1 :@" + strBuf.toString().substring(0,strBuf.length()/2));
//				Log.i("", "msg 2 :@" + strBuf.toString().substring(strBuf.length()/2));
//				JSONObject outer = new JSONObject(strBuf.toString());
//				
//
//				JSONArray pa = outer.getJSONArray("parameters");
//				if (pa != null && pa.length() > 0) {
//					return pa.getJSONObject(0);
//				}
//			} catch (JSONException e) {
//				Log.e("RequestPost", ":@" + e.getMessage());
//				return null;
//			}
//
//		} catch (SecurityException se) {
//			Log.e("RequestPost", "se:@" + se.getMessage());
//			return null;
//		} catch (InterruptedIOException ie) {
//			Log.e("RequestPost", "iioe:@" + ie.getMessage());
//			return null;
//		} catch (IOException e) {
//			Log.e("RequestPost", "ioe:@" + e.getMessage());
//			return null;
//		} catch (NullPointerException npe) {
//			Log.e("RequestPost", "pne:@" + npe.getMessage());
//			return null;
//		} finally {
//			try {
//				if (in != null)
//					in.close();
//				if (out != null)
//					out.close();
//				if (bos != null)
//					bos.close();
//				if (hc != null)
//					hc.disconnect();
//				this.stopConnect();
//			} catch (IOException ignored) {
//				this.stopConnect();
//			}
//			
//		}
//		return null;
//	}

	public static byte[] convertUnicode2UTF8Byte(String s) {
		byte b[];
		byte b1[];
		int len;
		int count = 0;
		char c;
		if (s == null || s.length() == 0)
			return null;
		len = s.length();
		b = new byte[len * 3];
		for (int i = 0; i < len; i++) {
			c = s.charAt(i);
			if (0x0080 > c) {
				b[count++] = (byte) c;
			} else if (0x0800 > c) {
				b[count++] = (byte) ((c >> 6) | 0xc0);
				b[count++] = (byte) ((c & 0x003F) | 0x80);
			} else {
				b[count++] = (byte) ((c >> 12) | 0xE0);
				b[count++] = (byte) (((c & 0x0FC0) >> 6) | 0x80);
				b[count++] = (byte) ((c & 0x003F) | 0x80);
			}
		}
		b1 = new byte[count];
		System.arraycopy(b, 0, b1, 0, count);
		b = null;
		return b1;
	}

	/**
	 * Method description
	 * 
	 */
	public static String convertByteArray2UTF8String(byte[] arrays) {
		if (arrays == null)
			return null;
		ByteArrayInputStream bais = new ByteArrayInputStream(arrays, 0, arrays.length);
		InputStreamReader isreader = null;

		try {
			isreader = new InputStreamReader(bais, "UTF-8");
		} catch (IOException ioe) {

		} catch (Exception exception1) {
			isreader = new InputStreamReader(bais);
		}
		String s;
		StringBuffer stringbuffer = new StringBuffer();
		int i = -1;
		do {
			try {
				if ((i = isreader.read()) == -1) {
					break;
				}
				char c = (char) i;
				if (c == '\n') {
					break;
				}
				if (c != '\r') {
					stringbuffer.append(c);
				}
				continue;
			} catch (IOException ioe) {

			} catch (Exception exception) {

			}
			break;
		} while (true);
		s = stringbuffer.toString();
		{
			try {
				if (isreader != null) {
					isreader.close();
					isreader = null;
				}
				if (bais != null) {
					bais.close();
					bais = null;
				}
			} catch (Exception exception3) {
			}
		}
		if (s.length() == 0) {
			if (i == -1) {
				return null;
			} else {
				return "";
			}
		} else {
			return s;
		}
	}

	private byte[] addCapacity(byte rece[]) {
		byte temp[] = new byte[rece.length + 1024];
		System.arraycopy(rece, 0, temp, 0, rece.length);
		return temp;
	}

}
